package com.cykj.admin.controller;

import com.cykj.common.dto.ResponseDTO;
import com.cykj.common.utils.ValidateCodeUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "ValidateCodeController",description = "验证码接口")
@CrossOrigin
@RestController
@RequestMapping("validate")
public class ValidateCodeController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
    * @Description: 获取验证码
    * @Param: []
    * @return: com.cykj.dto.ResponseDTO
    */
    @Operation(summary = "获取验证码接口")
    @Parameters({
            @Parameter(name = "userUnique",description = "唯一标识",required = true,in = ParameterIn.QUERY)
    })
    @GetMapping("get")
    public ResponseDTO getValidateCode(@RequestParam(value = "userUnique", required = false) String userUnique) {
        //判断有没有唯一标识 如果有 删除
        if (userUnique != null) {
            redisTemplate.delete(userUnique);
            System.out.println(userUnique + "的验证码删除成功了");
        }
        //1.创建验证码工具类的实例
        ValidateCodeUtil validateCodeUtil = new ValidateCodeUtil();
        //2.获取图形验证码
        String randomCodeImage = validateCodeUtil.getRandomCodeImage();
        //3.获取验证码的答案
        String code = validateCodeUtil.getCode();
        //4.存储验证码答案
        //获取唯一标识
        String unique = UUID.randomUUID().toString().replace("-", "");
        //把验证码存储到缓存当中
        redisTemplate.opsForValue().set(unique, code, 60, TimeUnit.SECONDS);
        //响应 图形验证码 + 唯一标识
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("code",randomCodeImage);
        hashMap.put("unique",unique);
        System.out.println("验证码答案: " + code);
        return ResponseDTO.success(hashMap);
    }
}